package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
)

var (
	key = []byte("gomicrohotel2020")
	iv  = []byte("2020083023505500")
)

// 加密数据
func Encrypt(data string) (string, error) {
	acesBlockEncrypt, err := aes.NewCipher((key))
	if err != nil {
		return "", err
	}
	blockSize := acesBlockEncrypt.BlockSize()
	content := PKCS5Padding([]byte(data), blockSize)

	encrypted := make([]byte, len(content))

	acesEncrypt := cipher.NewCBCEncrypter(acesBlockEncrypt, iv)
	acesEncrypt.CryptBlocks(encrypted, content)
	return hex.EncodeToString(encrypted), nil
}

//解密数据
func Decrypt(data string) (string, error) {
	acesBlockDecrypts, err := aes.NewCipher(key)
	if err != nil {
		println(err.Error())
		return "", err
	}
	acesDecrypts := cipher.NewCBCDecrypter(acesBlockDecrypts, iv)

	src, _ := hex.DecodeString(data)
	decrypted := make([]byte, len(src))
	acesDecrypts.CryptBlocks(decrypted, src)
	return string(PKCS5Trimming(decrypted)), nil
}

// PKCS5包装
func PKCS5Padding(text []byte, blockSize int) []byte {
	padding := blockSize - len(text)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(text, padText...)
}

// PKCS5解包装
func PKCS5Trimming(encrypt []byte) []byte {
	padding := encrypt[len(encrypt)-1]
	return encrypt[:len(encrypt)-int(padding)]
}
